<?php

namespace App\Http\Controllers;

use Inertia\Inertia;
use Inertia\Response;

class HomeController extends Controller
{
    /**
     * 显示首页
     */
    public function index(): Response
    {
        // 获取主分类
        $categories = \App\Models\Category::where('is_active', true)
        ->orderBy('sort_order')
        ->get();

        // 获取推荐产品
        $featuredProducts = \App\Models\Product::with(['variants' => function ($query) {
            $query->where('is_active', true)->orderBy('sort_order');
        }, 'categories', 'images'])
        ->where('is_active', true)
        ->where('is_featured', true)
        ->orderBy('sort_order')
        ->get();

        // 获取新品（按发布时间排序，取前4个）
        $newProducts = \App\Models\Product::with(['variants' => function ($query) {
            $query->where('is_active', true)->orderBy('sort_order');
        }, 'categories', 'images'])
        ->where('is_active', true)
        ->whereNotNull('published_at')
        ->orderBy('published_at', 'desc')
        ->limit(4)
        ->get();

        // 动态获取分类产品的辅助方法
        $getProductsByCategory = function ($categorySlug, $limit = 4) {
            return \App\Models\Product::with(['variants' => function ($query) {
                $query->where('is_active', true)->orderBy('sort_order');
            }, 'categories', 'images'])
            ->where('is_active', true)
            ->whereHas('categories', function ($query) use ($categorySlug) {
                $query->where('slug', $categorySlug)->where('is_active', true);
            })
            ->limit($limit)
            ->get();
        };

        // 从数据库动态查询分类 slug，按 sort_order 获取前几个特色分类
        $featuredCategories = \App\Models\Category::where('is_active', true)
            ->where('is_featured', true)
            ->orderBy('sort_order')
            ->limit(3)
            ->get(['slug', 'name']);

        // 根据查询到的分类获取产品
        $iphoneProducts = $featuredCategories->get(0) 
            ? $getProductsByCategory($featuredCategories->get(0)->slug) 
            : collect([]);
        
        $ipadProducts = $featuredCategories->get(1) 
            ? $getProductsByCategory($featuredCategories->get(1)->slug) 
            : collect([]);

        // 配件始终查询（如果有配件分类的话）
        $accessoriesCategory = \App\Models\Category::where('is_active', true)
            ->where('slug', 'like', '%accessories%')
            ->orWhere('slug', 'like', '%accessory%')
            ->orWhere('slug', 'like', '%配件%')
            ->first();
        
        $accessories = $accessoriesCategory 
            ? $getProductsByCategory($accessoriesCategory->slug) 
            : collect([]);

        return Inertia::render('Shop/Home', [
            'categories' => $categories,
            'featuredProducts' => $featuredProducts,
            'newProducts' => $newProducts,
            'iphoneProducts' => $iphoneProducts,
            'ipadProducts' => $ipadProducts,
            'accessories' => $accessories
        ]);
    }
}
